// 导入vue-router相关类型
import type { RouteRecordRaw } from 'vue-router'
import { createWebHistory, createRouter } from 'vue-router'
import Home from '@/views/Home.vue'
import { useUserStore } from '@/store/user'

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/LoginView.vue'),
    meta: {
      requiresAuth: false,
      title: '登录 - XLChat'
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/home/chat',
    meta: {
      requiresAuth: true,
      title: '首页 - XLChat'
    },
    children: [
      {
        path: 'chat',
        name: 'Chat',
        component: () => import('@/views/ChatView.vue'),
        meta: {
          requiresAuth: true,
          title: '聊天 - XLChat'
        }
      },
      {
        path: 'contacts',
        name: 'Contacts',
        component: () => import('@/views/ContactsView.vue'),
        meta: {
          requiresAuth: true,
          title: '联系人 - XLChat'
        }
      },
      {
        path: 'files',
        name: 'Files',
        component: () => import('@/views/FilesView.vue'),
        meta: {
          requiresAuth: true,
          title: '文件 - XLChat'
        }
      },
      {
        path: 'theme',
        name: 'Theme',
        component: () => import('@/views/ThemeView.vue'),
        meta: {
          requiresAuth: true,
          title: '主题设置 - XLChat'
        }
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/components/LoginView/About.vue'),
    meta: {
      requiresAuth: false,
      title: '关于我们 - XLChat'
    }
  },
  {
    path: '/preview',
    name: 'Preview',
    component: () => import('@/components/PreView/PreviewWindow.vue'),
    meta: {
      requiresAuth: false,
      title: '文件预览 - XLChat'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = (to.meta.title as string) || 'XLChat'

  // 跳过不需要认证的路由
  if (to.meta.requiresAuth === false) {
    // 如果已登录且要去登录页，重定向到首页
    const userStore = useUserStore()
    if (to.path === '/login' && userStore.isLoggedIn) {
      next('/home')
      return
    }
    next()
    return
  }

  // 检查是否需要认证
  if (to.matched.some((record) => record.meta.requiresAuth !== false)) {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) {
      // 未登录，重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }

  next()
})

export default router
